﻿using ExamDemo.Data;
using ExamDemo.Models;
using ExamDemo.paramModel;
using System.Linq;
using System.Web.Mvc;

namespace ExamDemo.Controllers
{
    public class UserController : Controller
    {
        private MyDb db = new MyDb();
        // GET: User
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LoginVtr(Login model)
        {
            var username = model.UserName.Trim();
            var pwd = model.PassWord.Trim();
            if (username.Length > 0 && pwd.Length > 0)
            {
                var user = db.Users.Where(u => u.UserName == username).FirstOrDefault();

                if (user != null && user.PassWord == pwd)
                {
                    Session["UserName"] = username;
                    Session["Id"] = user.Id;

                    return Json(new
                    {
                        code = 200,
                        msg = "登录成功"
                    });
                }
                else
                {
                    return Json(new
                    {
                        code = 520,
                        msg = "该用户还未注册，请尝试注册"
                    });
                }

            }
            else
            {
                return Json(new
                {
                    code = 1231,
                    msg = "请输入必要信息"
                });
            }
        }
        [HttpPost]
        public ActionResult RegisterVtr(Register model)
        {
            var username = model.UserName.Trim();
            var pwd = model.PassWord.Trim();
            var configmPwd = model.ConfirmPassword.Trim();

            if (username.Length > 0 && pwd.Length > 0 && pwd == configmPwd)
            {
                var user = db.Users.Where(u => u.UserName == username).FirstOrDefault();

                if (user == null)
                {
                    db.Users.Add(new Users
                    {
                        UserName = username,
                        PassWord = pwd

                    });

                    db.SaveChanges();

                    return Json(new
                    {
                        code = 200,
                        msg = "注册成功"
                    });
                }
                else
                {
                    return Json(new
                    {
                        code = 2333,
                        msg = "该用户以注册，请尝试登录"
                    });
                }

            }
            else
            {
                return Json(new
                {
                    code = 1231,
                    msg = "注册失败，请重新尝试"
                });
            }
        }
    }
}